﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AWSInterface.AmazonServiceSDK;
using System.Net;
using System.ServiceModel;
using Amazon;
using Amazon.EC2;

namespace AWSInterface
{
    public class AWSSearch
    {
        // Amazon Web Service ID.
        private const string AmazonUserID = ""; // Insert your AWS-KeyID here!
        private const string AmazonUserKey = ""; // Insert your AWS-Secret-Key here!

        public List<AWSResult> searchMovie(string sSearchPattern)
        {
            List<AWSResult> lResults = new List<AWSResult>();

            try
            {
                // create a WCF Amazon ECS client
                BasicHttpBinding oBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
                oBinding.MaxReceivedMessageSize = int.MaxValue;
                AWSECommerceServicePortTypeClient client = new AWSECommerceServicePortTypeClient(oBinding, new EndpointAddress("https://ecs.amazonaws.de/onca/soap?Service=AWSECommerceService"));

                // add authentication to ECS client
                client.ChannelFactory.Endpoint.Behaviors.Add(new AmazonSigningEndpointBehavior(AmazonUserID, AmazonUserKey));

                // prepare an ItemSearch request
                ItemSearchRequest request = new ItemSearchRequest();
                request.SearchIndex = "Video";
                request.Title = sSearchPattern;
                request.ResponseGroup = new string[] { "Large" };

                ItemSearch itemSearch = new ItemSearch();
                itemSearch.Request = new ItemSearchRequest[] { request };
                itemSearch.AWSAccessKeyId = AmazonUserID;
                itemSearch.AssociateTag = ""; // Insert your AWS-AssociateTag here!
                //itemSearch.SubscriptionId   = AmazonUserID;
                //request.

                // issue the ItemSearch request
                ItemSearchResponse response = client.ItemSearch(itemSearch);

                // write out the results
                if (response.Items != null && response.Items.Count() > 0 && response.Items[0].Item != null)
                {
                    foreach (var item in response.Items[0].Item)
                    {
                        AWSResult oResult = new AWSResult();
                        oResult.Title = item.ItemAttributes.Title;
                        oResult.ASIN = item.ASIN;
                        if (item.EditorialReviews != null)
                            oResult.Description = FilterHTMLText(item.EditorialReviews[0].Content);
                        oResult.Cast = generateCastString(item.ItemAttributes.Actor);
                        oResult.Director = generateDirectorString(item.ItemAttributes.Director);
                        oResult.DetailPageURL = item.DetailPageURL;
                        oResult.TheatricalRelease = item.ItemAttributes.ReleaseDate;
                        if (item.LargeImage != null)
                            oResult.ImageLargeURL = item.LargeImage.URL;
                        if (item.MediumImage != null)
                            oResult.Thumbnail = new System.Windows.Media.Imaging.BitmapImage(new Uri(item.MediumImage.URL, UriKind.Absolute));

                        lResults.Add(oResult);
                    }
                }
            }
            catch (Exception ex)
            {
                return null;
            }

            return lResults;
        }

        /// <summary>
        /// Utility function that strips HTML tags and whitespace from the input string.
        /// </summary>
        /// <param name="htmlText"></param>
        /// <remarks>Used by GetListOfDVDs method. </remarks>
        private string FilterHTMLText(string htmlText)
        {
            string filteredText = "";

            if (htmlText != null)
            {
                filteredText = htmlText;

                //remove HTML tags using a regular expression
                filteredText = htmlText.Replace("<br>", Environment.NewLine);
                filteredText = htmlText.Replace("<br />", Environment.NewLine);
                filteredText = htmlText.Replace("<br/>", Environment.NewLine);
                filteredText = htmlText.Replace("</p>", Environment.NewLine + Environment.NewLine);
                filteredText = htmlText.Replace("</h1>", Environment.NewLine + Environment.NewLine);
                filteredText = htmlText.Replace("</h2>", Environment.NewLine + Environment.NewLine);

                filteredText = System.Text.RegularExpressions.Regex.Replace(filteredText, "(<[^>]+>)", "");

                //remove whitespace characters using a regular expression
                filteredText = System.Text.RegularExpressions.Regex.Replace(filteredText, "&(nbsp|#160);", "");

                //optional: format out additional characters 
                //...
            }

            return filteredText;
        }

        /// <summary>
        /// Generate Comma-Seperated String from Actors-String-Array.
        /// </summary>
        /// <param name="Cast"></param>
        /// <returns></returns>
        private string generateCastString(string[] Cast)
        {
            string sCast = String.Empty;

            if (Cast != null && Cast.Count() > 0)
            {
                foreach (string sActor in Cast)
                {
                    sCast += sActor + ", ";
                }

                sCast = sCast.Remove(sCast.Length - 2);
            }

            return sCast;
        }

        /// <summary>
        /// Generate Comma-Seperated String from Director-String-Array.
        /// </summary>
        /// <param name="Cast"></param>
        /// <returns></returns>
        private string generateDirectorString(string[] Directors)
        {
            string sDirectors = String.Empty;

            if (Directors != null && Directors.Count() > 0)
            {
                foreach (string sDirector in Directors)
                {
                    sDirectors += sDirector + ", ";
                }

                sDirectors = sDirectors.Remove(sDirectors.Length - 2);
            }

            return sDirectors;
        }
        
    }
}
